#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API路径探索脚本
用于找出正确的API端点路径结构
"""

import requests
import json
import time

def test_endpoint(url, method='get', data=None):
    """测试单个API端点并返回结果"""
    try:
        if method.lower() == 'get':
            response = requests.get(url, timeout=10)
        elif method.lower() == 'post':
            response = requests.post(url, json=data, timeout=10)
        
        print(f"URL: {url}")
        print(f"方法: {method.upper()}")
        print(f"状态码: {response.status_code}")
        
        # 尝试解析JSON响应
        try:
            if response.text.strip():
                json_data = response.json()
                print(f"响应内容: {json.dumps(json_data, indent=2, ensure_ascii=False)}")
            else:
                print("响应内容: 空")
        except:
            print(f"响应内容: {response.text[:200]}..." if len(response.text) > 200 else f"响应内容: {response.text}")
        
        print("-" * 60)
        return response.status_code, response
    except Exception as e:
        print(f"URL: {url}")
        print(f"方法: {method.upper()}")
        print(f"错误: {str(e)}")
        print("-" * 60)
        return None, None

def main():
    """主函数"""
    print("=" * 60)
    print("API路径探索工具")
    print("=" * 60)
    
    # 基础URL
    base_url = "http://127.0.0.1:5000"
    
    print(f"探索API基础URL: {base_url}\n")
    
    # 首先确认健康检查API
    print("测试健康检查API...")
    test_endpoint(f"{base_url}/health")
    
    # 测试根路径
    print("\n测试根路径...")
    test_endpoint(f"{base_url}/")
    
    # 尝试不同的API路径组合
    possible_paths = [
        # 测试脚本管理API的可能路径
        "/scripts",
        "/api/scripts",
        "/v1/scripts",
        "/vulnerability/scripts",
        "/scanner/scripts",
        
        # 测试其他可能的API端点
        "/api",
        "/v1",
        "/docs",
        "/swagger",
        "/redoc",
        "/status",
        "/scan",
        "/vulnerabilities",
        "/tasks",
    ]
    
    print("\n测试可能的API路径...")
    for path in possible_paths:
        test_endpoint(f"{base_url}{path}")
        time.sleep(0.5)  # 添加短暂延迟，避免请求过快
    
    print("\nAPI路径探索完成！")
    print("根据返回结果，选择正确的路径前缀进行进一步测试。")

if __name__ == "__main__":
    main()